const {
  Service,
} = require('uni-cloud-router')
const {
  TaskType,
  PointsAction,
} = require('../constants/const')
const {
  generateToken,
} = require('../utils/Auth')
const { getDate } = require('../utils/Date')
const ResponseUtil = require('../utils/Response')

module.exports = class PointsService extends Service {
  async list(data) {
    const { openId } = data
    const list = await this.db.collection('points').where({
      createdBy: openId,
    }).get()

    return ResponseUtil.success(list.data.map((item) => {
      return {
        id: item._id,
        name: item.name,
        point: item.point,
      }
    }))
  }

  async add(data) {
    const { id, name, point, openId } = data
    if (id) {
      await this.db.collection('points').doc(id).update({
        name,
        point,
        updateAt: new Date(),
      })
    }
    else {
      await this.db.collection('points').add({
        createdBy: openId,
        name,
        point,
        createdAt: new Date(),
        updateAt: new Date(),
      })
    }
    return ResponseUtil.success(null, '成功')
  }

  async remove(data) {
    const { openId, id } = data
	console.log('remove')
    await this.db.collection('points').doc(id).remove()
    return ResponseUtil.success(null, '成功')
  }

  async transaction(data) {
    const { childId, id, type } = data

    const db = this.db
    const dbCmd = db.command
    // 事务
    const transaction = await db.startTransaction()

    try {
      // 当前任务或者商品的信息
      const points = {}
      // 获取当前子女已有的积分
      const result = await db.collection('child').doc(childId).get()
      const score = result.data[0]?.score || 0

      // 奖品消费积分
      if (type === PointsAction.Exchange) {
        const result = await db.collection('points').doc(id).get()
        points.name = result.data[0].name
        points.point = result.data[0].point
        points.id = result.data[0]._id
        if (score < Number(points.point || 0)) {
          return ResponseUtil.error('积分不足')
        }
      }

      // 任务获得积分
      if (type === PointsAction.Task) {
        const result = await db.collection('daily_task_records').where({
          childId,
          recordDate: getDate(),
        }).get()
        result.data[0]?.tasks?.map((item) => {
          if (item.taskId === id) {
            points.name = result.data[0].taskTitle
            points.point = result.data[0].taskPoint
            points.id = result.data[0]._id
          }
          return item
        })
      }

      await transaction.collection('child').doc(childId).update({
        score: dbCmd.inc(type === PointsAction.Task ? points.point : -points.point),
      })

      await transaction.collection('points_transaction').add({
        type,
        childId,
        point: points.point,
        name: points.name,
        createAt: new Date(),
        linked: points.id,
      })

      await transaction.commit()

      return ResponseUtil.success(null, '兑换成功')
    }
    catch (err) {
      console.error(err)
      transaction.rollback()
      return ResponseUtil.error('兑换失败')
    }
  }
}
